<?php


namespace app\index\controller;
use app\common\model\User as UserModel;
use app\common\model\Userinfo as UserInfoModel;
use app\common\model\Company as CompanyModel;
use app\common\model\Goods as GoodsModel;
use app\common\model\Sell as SellModel;
use app\common\model\Produce as ProduceModel;
use app\common\model\Cart as CartModel;
use think\Request;
use think\Db;
use think\Session;

use think\Controller;

class User extends Controller
{
    public function home(){
        return $this->fetch();
    }

    //修改密码
    public function updPwd(){
        return $this->fetch();
    }

    //退出登录
    public function logout()
    {
        session(null);
        return $this->success('已成功退出！','user/home');
    }

    //购物车
    public function cart(){
        return $this->fetch();
    }
    public function getCart(){
        $cart = new CartModel();
        $goodsList = Db::query("select * from produce join goods using(`gID`) where pID in (select pID from cart where uID=:uID)",
        ['uID'=>Session::get('uID')]);
        // 改变原数组需要加 & 表示引用，否则原数组不变
        foreach ($goodsList as &$item){
            $item['num'] = $cart->where('uID',Session::get('uID'))->where('pID',$item['pID'])->find()['num'];
            $item['ID'] = $cart->where('uID',Session::get('uID'))->where('pID',$item['pID'])->find()['ID'];
        }
        return $goodsList;
    }

    //加数量
    public function addNum(){
        $ID = $this->request->post()['ID'];
        Db::table('cart')->where('ID',$ID)->update([ 'num' => Db::raw('num+1') ]);
    }
    //减数量
    public function minusNum(){
        $ID = $this->request->post()['ID'];
        Db::table('cart')->where('ID',$ID)->update([ 'num' => Db::raw('num-1') ]);
    }
    //直接修改数量
    public function changeNum(){
        $data = $this->request->post();
        $cart = new CartModel();
        $cart->isUpdate(true)->allowField(true)->save($data);
    }

    //删除所选
    public function doDelete(){
        $data = $this->request->post()['ids'];
        $ids = explode(',',$data);
        Db::table('cart')->delete($ids);
        $result['success'] = "true";
        return $result;
    }

    //跳转登录
    public function userLogin(){
        return $this->fetch();
    }
    //登录操作
    public function doLogin(){
        $data = $this->request->post();
        $one = Db::query("select * from userinfo join user USING(`uID`) where name=:name",
            ['name'=>$data['name']])[0];
        if($one){
            if($one['pwd'] == $data['pwd']){
                Session::set('name',$one['name']);
                Session::set('uID',$one['uID']);
                echo "<meta http-equiv='Content-Type'' content='text/html; charset=utf-8'>";
                echo "<script charset='utf-8' type='text/javascript'>alert('成功登录！');window.location.href='home';</script>";
            }else{
                echo "<meta http-equiv='Content-Type'' content='text/html; charset=utf-8'>";
                echo "<script charset='utf-8' type='text/javascript'>alert('密码错误！');window.location.href='userLogin';</script>";
            }
        } else{
            echo "<meta http-equiv='Content-Type'' content='text/html; charset=utf-8'>";
            echo "<script charset='utf-8' type='text/javascript'>alert('用户名错误！');window.location.href='userLogin';</script>";
        }

    }


    //跳转注册
    public function userRegister(){
        $regionList = Db::table('region')->select();
        $this->assign("regionList",$regionList);
        return $this->fetch();
    }
    //查看是否已有用户名
    public function getName(){
        $post_name = $this->request->post()['name'];
        $user = new UserInfoModel();
        $name = $user->where('name','eq',$post_name)->find();
//        dump($name);
        if($name){
            $result['valid'] = "false";
        }else{
            $result['valid'] = "true";
        }
        return $result;
    }
    //实现注册
    public function do_register(){
        $form = $this->request->post();
//        dump($form);
        $userinfo = new UserInfoModel();
        $user = new UserModel();
        //先存userinfo表
        $userinfo->allowField(true)->save($form);
        //设置uID相同
        $uID = $userinfo->where('name','=',$form['name'])->find()['uID'];
        $form['uID'] = $uID;

        //存入user
        $user->allowField(true)->save($form);

        $result['success'] = "true";
        return $result;
    }

    // 根据销售码溯源
    public function searchByCode(){
        $data = $this->request->post()['gSellCode'];
        if($data){
            $result = Db::query("select p.*,g.* from produce p join goods g using(`gID`)
            where gID=(select gID from goods where gSellCode=$data and gNum>0)");
            if($result){
                $this->assign([
                    'currentText' => $data,
                    'result' => $result,
                ]);
                return $this->fetch();
            }else{
                $this->assign([
                    'currentText' => $data,
                ]);
                return $this->fetch('notFind');
            }
        }else{
            return $this->redirect('home');
        }
    }

    // 获取某一产品详情
    public function getDetail(){
        $pID = $this->request->post()['pID'];
        $one = Db::query("select * from produce join goods using(`gID`) where pID=:pID",
        ['pID'=>$pID])[0];
        $one['cName'] = Db::query("select name from company where cID=:cID",
        ['cID'=>$one['cID']])[0]['name'];

        return json($one);
    }

    //加入购物车
    public function addCart(){
        $data = $this->request->post();
        $cart = new CartModel();
        $one = $cart->where('uID','eq',$data['uID'])
            ->where('pID','eq',$data['pID'])->find();
        if($one){
            Db::table('cart')->where('ID',$one['ID'])->update([ 'num' => Db::raw('num+1') ]);
        }else{
            $cart->allowField(true)->save($data);
        }
        $result['success']="true";
        return $result;
    }

    //结算界面
    public function pay(){
        $data = $this->request->post()['ids'];
        $ids = explode(',',$data);
        $cart = new CartModel();
        $payList = $cart->where('ID','IN',$ids)->select();
        $payPrice = 0.0;
        foreach ($payList as &$item){
            $item['detail'] = Db::query("select * from produce join goods using(`gID`) where pID in (select pID from cart where ID=:ID)",
            ['ID'=>$item['ID']])[0];
            $item['totalPrice'] = $item['detail']['gPrice'] * $item['num'];
            $payPrice = $payPrice + $item['totalPrice'];
        }
        $this->assign([
            'payList' => $payList,
            'payPrice' => $payPrice,
        ]);
        return $this->fetch();
    }
    public function doPay(){
        $data = $this->request->post();
        $cart = new CartModel();
        $produce = new ProduceModel();
        foreach ($data as $item){
            $one = $cart->where('ID',$item)->find();
            $pID = $one['pID'];
            $num = (int)$one['num'];
            Db::query("update produce set gNum = gNum - :num where pID = :pID",
            ['num'=>$num, 'pID'=>$pID]);
            $cart->where('ID',$item)->delete();
        }
        $this->redirect('cart');
        $this->redirect('cart');
    }

    // 企业查询
    public function company(){
        return $this->fetch();
    }


}